package com.hyt.it.ogt.opertaion.track.rpc;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

import static com.hyt.it.ogt.opertaion.track.constants.OperationTrackConstants.HEADER_TOKEN;

/**
 * @author 朱振宇
 * @since 2022-11-24
 */
@Component
@Slf4j
@ConditionalOnProperty(value = "operationTrack.enabled", havingValue = "true", matchIfMissing = true)
public class OperationTrackFeignInterceptor implements RequestInterceptor {

    private static final ThreadLocal<Map<String, Object>> operationTrackThreadLocal =ThreadLocal.withInitial(HashMap::new);

    public static void setOperationTrackThreadLocal(String key, String val) {
        operationTrackThreadLocal.get().put(key, val);
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        if(operationTrackThreadLocal.get().get(HEADER_TOKEN) != null) {
            requestTemplate.header(HEADER_TOKEN, operationTrackThreadLocal.get().get(HEADER_TOKEN).toString());
            operationTrackThreadLocal.remove();
        }
    }
}
